/**
* author:
* date: 2024
* description: 详情
**/
<template>
    <div class="bak-color-white detail-warp" v-loading="loading">
      <div class="detail-tabs flex-b-c">
        <div class="detail-tabs-item">
          <span class="course-type flex-c can-click" v-for="(item, i) in detailTabs" :key="i" :class="{'active': item.active}" @click="changeTab(item)">{{ item.contentName }}</span>
        </div>
        <canvas ref="qrCodeCanvas" class="qr-code"></canvas>
      </div>
      <div class="detail-iframe">
        <div v-if="fileData.contentUlrArr && fileData.contentUlrArr[0] && fileData.contentUlrArr[0].fileSuffix && fileData.contentUlrArr[0].fileSuffix === '.pdf'"
             class="full-screen-btn flex-c can-click"
             @click="fullScreen">
          <i class="el-icon-full-screen"></i>
        </div>
        <div v-if="fileData.fileType === 1" style="width: 100%;height: 100%">
          <iframe
            v-if="fileData.contentUlrArr && fileData.contentUlrArr[0] && fileData.contentUlrArr[0].fileSuffix && fileData.contentUlrArr[0].fileSuffix === '.pdf'"
            width="100%"
            height="100%"
            frameborder="0"
            :src="(fileData.contentUlrArr && fileData.contentUlrArr[0] && fileData.contentUlrArr[0].pdfUrl) ? fileData.contentUlrArr[0].pdfUrl : ''">
          </iframe>
          <iframe
            v-if="fileData.contentUlrArr && fileData.contentUlrArr[0] && fileData.contentUlrArr[0].fileSuffix &&
            (fileData.contentUlrArr[0].fileSuffix === '.ppt' ||
            fileData.contentUlrArr[0].fileSuffix === '.docx' ||
            fileData.contentUlrArr[0].fileSuffix === '.doc')"
            style="width: 100%;height: 100%"
            :src="`https://view.officeapps.live.com/op/${(sessionStorageWrap.permissions == 1) ? 'view' : 'embed'}.aspx?src=${fileData.contentUlrArr[0].fileUrl}`">
          </iframe>
          <iframe
            v-if="fileData.contentUlrArr && fileData.contentUlrArr[0] && fileData.contentUlrArr[0].fileSuffix &&
            (fileData.contentUlrArr[0].fileSuffix === '.pptx')"
            style="width: 100%;height: 100%"
            :src="`https://view.xdocin.com/view?src=${fileData.contentUlrArr[0].fileUrl}`">
          </iframe>
          <i class="ppt-download el-icon-download fs-14"
             @click="pptDownload"
             v-if="(fileData.contentUlrArr && fileData.contentUlrArr[0] && fileData.contentUlrArr[0].fileSuffix && fileData.contentUlrArr[0].fileSuffix === '.pptx') &&
             (sessionStorageWrap.permissions == 1)"></i>
        </div>
        <el-collapse v-else-if="fileData.fileType === 2" style="padding: 0 0.1rem">
          <el-collapse-item v-for="(item, i) in fileData.contentUlrArr" :key="i" :title="item.fileName" :name="i+1">
            <video
              width="100%"
              height="100%"
              :controlsList="(sessionStorageWrap.permissions == 1) ? '' : 'nodownload'"
              controls
              :src="item.fileUrl ? item.fileUrl : ''">
            </video>
          </el-collapse-item>
        </el-collapse>
        <el-carousel v-else-if="fileData.fileType === 3" class="file-carousel" trigger="click" height="100%">
          <el-carousel-item v-for="(item, i) in fileData.contentUlrArr" :key="i">
            <img :src="item.fileUrl">
          </el-carousel-item>
        </el-carousel>
        <el-table  v-else-if="fileData.fileType === 4" :data="fileData.contentUlrArr">
          <el-table-column label="标题" prop="fileName"></el-table-column>
          <el-table-column label="文件类型" prop="fileSuffix"></el-table-column>
          <el-table-column label="上传时间">
            <template slot-scope="{ row }">
              <span>{{ getTime(row.updateTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-if="sessionStorageWrap.permissions == 1" slot-scope="{ row }">
              <a :href="row.fileUrl" class="a-link" target="downloadFile" download>下载</a>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog custom-class="full-screen-dialog" :visible.sync="fullScreenDialog">
        <div class="dialog-full-screen flex-c can-click" @click="closeDialog">
          <i class="el-icon-full-screen"></i>
        </div>
        <iframe width="100%"
                height="100%"
                frameborder="0"
                :src="(fileData.contentUlrArr && fileData.contentUlrArr[0] && fileData.contentUlrArr[0].pdfUrl) ? fileData.contentUlrArr[0].pdfUrl : ''"></iframe>
      </el-dialog>
    </div>
</template>

<script>
  import axios from 'axios';
  import QRCode from 'qrcode'
  // import VueOfficeDocx from '@vue-office/docx'
    export default {
      name: "detail",
      props: {
        chooseTreeData: {
          type: Object,
          default: {}
        },
      },
      components:{
        // VueOfficeDocx
      },
      data(){
        let query = this.$route.query;
          return {
            src: 'https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf',
            detailTabs: [],
            courseId: query.id,
            loading: false,
            fileData: {},
            pdfSrc: '',
            fullScreenDialog: false,
            sessionStorageWrap: null
          }
      },
      watch: {
        chooseTreeData(val){
          this.chooseTreeData = val;
          this.getData();
        }
      },
      created(){
        this.sessionStorageWrap = sessionStorage;
        this.getData();
      },
      methods: {
        /**
        * 根据地址生成二维码
        **/
        generateQRCode(){
          const canvas = this.$refs.qrCodeCanvas;
          let url = window.location.href;
          const options = { // 设置二维码的参数，例如大小、边距等
            margin: 0
          };
          QRCode.toCanvas(canvas, url, options, error => {
            if (error) console.error(error)
          })
        },
        changeTab(item){
          for(let item of this.detailTabs){
            item.active = false;
          }
          item.active = true;
          this.fileData = item;
        },
        getObjectURL(file){
          let url = null;
          if (window.createObjectURL != undefined) {
            url = window.createObjectURL(file);
          } else if (window.webkitURL != undefined) {
            try {
              url = window.webkitURL.createObjectURL(file);
            } catch (error) {}
          } else if (window.URL != undefined) {
            try {
              url = window.URL.createObjectURL(file);
            } catch (error) {}
          }
          return url;
        },
        getData(){
          this.loading = true;
          let param = {
            courseOverviewId: this.chooseTreeData.courseOverviewId,
            courseChapterId: this.chooseTreeData.id,
          };
          this.Request.courseChapterInfo({params: param}).then(res=>{
            this.loading = false;
            this.detailTabs = res.data || [];
            if(this.detailTabs.length){
              // 设置tabs的active
              this.detailTabs.forEach((item)=>{
                this.$set(item, 'active', false);
                if(item.contentUlr !== ''){
                  this.$set(item, 'contentUlrArr', JSON.parse(item.contentUlr));
                }else {
                  this.$set(item, 'contentUlrArr', []);
                }
              });
              // 如果是fileType=1（是pdf文件），设置预览的地址
              this.detailTabs.forEach((item)=>{
                if(item.fileType === 1 && item.contentUlrArr.length){
                  item.contentUlrArr[0].fileUrl = item.contentUlrArr[0].fileUrl.replace(/http:/g, 'https:');
                  this.getPdfUrl(item.contentUlrArr[0].fileUrl).then(res=>{
                    this.$set(item.contentUlrArr[0], 'pdfUrl', res)
                  })
                }
              });
              this.detailTabs[0].active = true;
              this.fileData = this.detailTabs[0];
              // 根据地址生成二维码
              this.generateQRCode();
            }else {
              this.fileData = {};
            }
          }).catch(()=>{
            this.detailTabs = [];
            this.fileData = {};
            this.loading = false;
          })
        },
        getPdfUrl(fileUrl){
          let promise = new Promise((resolve, reject)=>{
            axios({
              method: 'get',
              url: fileUrl,
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
              },
              responseType: 'blob' //设置响应的数据类型为一个包含二进制数据的 Blob 对象，必须设置！！！
            }).then(res => {
              let src = this.getObjectURL(res.data); // 将返回的数据流转换为url
              return resolve(src);
            })
          });
          return promise;
        },
        getTime(val){
          return this.$moment(val).format('YYYY-MM-DD HH:mm:ss')
        },
        downloadFile(row){
          let fileName = row.fileName;
          let blob = new Blob([row.fileUrl],{type:'application/octet-stream'})
          let href = window.URL.createObjectURL(blob)
          let downloadDom = document.createElement('a')
          downloadDom.href = href
          downloadDom.download = fileName;
          document.body.appendChild(downloadDom);
          downloadDom.click()
          document.body.removeChild(downloadDom);
          window.URL.revokeObjectURL(href);
        },
        fullScreen(){
          this.fullScreenDialog = true;
        },
        closeDialog(){
          this.fullScreenDialog = false;
        },
        pptDownload(){
          const eleLink = document.createElement("a");
          eleLink.style.display = "none";
          eleLink.setAttribute("download", this.fileData.contentUlrArr[0].fileName);
          eleLink.setAttribute("href", this.fileData.contentUlrArr[0].fileUrl);
          document.body.appendChild(eleLink);
          eleLink.click();
          document.body.removeChild(eleLink);
        },
      }
    }
</script>

<style scoped lang="scss">
  @import "../../../css/module/courseDetail";
</style>
